package cn.wolfcode.web.controller;


import cn.wolfcode.common.anno.RequestUser;
import cn.wolfcode.common.constants.CommonConstants;
import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.PayLog;
import cn.wolfcode.domain.PayResult;
import cn.wolfcode.domain.PayVo;
import cn.wolfcode.feign.PayFeignApi;
import cn.wolfcode.service.IOrderInfoService;
import com.mysql.cj.protocol.PacketReceivedTimeHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {
    private final IOrderInfoService orderInfoService;

    public OrderPayController(IOrderInfoService orderInfoService) {
        this.orderInfoService = orderInfoService;
    }

    /**
     * 订单支付
     * @param orderNo 订单编号
     * @param type 支付类型 {0：在线支付 1：积分支付}
     * @return 支付页面的URL
     */
    @RequireLogin
    @GetMapping("/pay")
    public Result<String> doPay(String orderNo, Integer type, @RequestUser UserInfo userInfo){
        //在线支付-支付宝支付
        if(type == OrderInfo.PAY_TYPE_ONLINE){
            return Result.success(orderInfoService.onlinePay(orderNo,userInfo.getPhone()));
        }
        //积分支付
        orderInfoService.integralPay(orderNo,userInfo.getPhone());
        return Result.success();
    }

    /**
     * 远程调用改变订单状态以及记录支付记录
     * @param payResult
     * @return
     */
    @PostMapping("/changeOrderStateAndPayLog")
    public Result<?> doChangeOrderStateAndPayLog(@RequestBody PayResult payResult){
        //需要参数
        //1.修改订单状态： order_no(订单号),status(支付状态),pay_date(支付时间),pay_type(支付类型)
        //2.记录支付记录：out_trade_no(订单号),trade_no(支付宝交易流水号),notify_time(支付时间),total_amount(支付总金额),pay_type(支付类型)
        orderInfoService.changeOrderStateAndPayLog(payResult);
        return Result.success();
    }

    /**
     * 申请退款
     * @param orderNo 订单编号
     * @return
     */
    @GetMapping("/refund")
    public Result<?> refund(String orderNo){
        orderInfoService.refundByAlipay(orderNo);
        return Result.success();
    }
}
